<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Lines extends Model
{
    /**
     * 定义主键字段
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 定义表名，不含前缀
     *
     * @var string
     */
    protected $table      = 'wd_bf_lines';

    /**
     * 定义拒绝保存的字段
     *
     * @var array
     */
    protected $guarded    = ['id'];

    /**
     * 开启laravel默认的时间记录
     *
     * @var bool
     */
    public $timestamps = true;

    /**
     * 计划任务分润助推
     *
     * @param int $pro_money    助推利润总额
     * @param int $shop_id      获益助推的商户队列
     * @param int $user_id      推广用户id
     * @param int $order_sn     助推订单来源
     */
    public static function assist($pro_money , $shop_id=0 , $user_id=0 , $order_sn='')
    {
        // 开启事务
        DB::beginTransaction();

        // 初始化
        $pro_log = array();

        try{

            // 利润分配
            do{

                // 助推推广人
                if($user_id>0){

                    // 定向助推推广用户
                    $pro_info = Lines::where('status',1)
                                ->where('user_id',$user_id)
                                ->orderBy('displayorder','asc')
                                ->first();

                    // 推广用户无队列
                    if(!$pro_info){

                        // 助推推广用户所在店铺
                        $tg_id_shop = User::where('id',$user_id)->value('shop_id');

                        // 店铺存在
                        if($tg_id_shop>0){

                            // 店铺队列
                            $pro_info   = Lines::where('status',1)
                                        ->where('delivery_point',$tg_id_shop)
                                        ->orderBy('displayorder','asc')
                                        ->first();

                            // 记录推广人店铺溢出日志
                            if(!$pro_info){

                                $flow_in = new FlowIn;
                                $flow_in->order_id  = '分润'.$order_sn;         // 收益溢出来源订单
                                $flow_in->money     = $pro_money;               // 溢出金额
                                $flow_in->shop_id   = $tg_id_shop;              // 商户id
                                $flow_in->note      = "分润助推收益溢出";       // 记录日志
                                $flow_in->save();

                                // 跳出循环
                                break;
                            }

                        }else{

                            // 推广人未绑定店铺，系统默认店铺溢出日志
                            $flow_in = new FlowIn;
                            $flow_in->order_id  = '分润'.$order_sn;                             // 收益溢出来源订单
                            $flow_in->money     = $pro_money;                                   // 溢出金额
                            $flow_in->shop_id   = 0;                                            // 商户id
                            $flow_in->note      = "分润助推收益溢出，推广用户未绑定店铺";       // 记录日志
                            $flow_in->save();

                            // 跳出循环
                            break;
                        }
                        
                    }

                // 助推用户店铺
                }else{

                    // 寻找用户所在店铺的队列
                    $pro_info = Lines::where('status',1)
                                ->where('delivery_point',$shop_id)
                                ->orderBy('displayorder','asc')
                                ->first();  

                }

                

                if(!$pro_info){
                    // 无受益人情况下 将钱打入商户收益 -- 利润商户溢出收益
                    $flow_in = new FlowIn;
                    $flow_in->order_id  = '分润'.$order_sn;                 // 收益溢出来源订单
                    $flow_in->money     = $pro_money;                       // 溢出金额
                    $flow_in->shop_id   = $shop_id;                         // 商户id
                    $flow_in->note      = "分润助推收益溢出";               // 记录日志
                    $flow_in->save();

                    // 跳出循环
                    break;
                }

                // 用户剩余收益 = 待返金额 - 已收益金额
                $need = $pro_info['money'] - $pro_info['proceeds'];

                // 初始化变量 -- 获取的收益
                $get_pro = 0;

                if($pro_money>=$need){
                    // 本次获取的收益
                    $get_pro = $need;

                    // 获益后直接出局
                    $re_pay_pro = Lines::where('order_id',$pro_info['order_id'])
                                ->update([
                                    'proceeds'          => $pro_info['proceeds']+$need, 
                                    'assist_proceeds'   => $pro_info['assist_proceeds']+$need,
                                    'status'            => 2 , 
                                    'out_time'          => time()
                                ]);

                    // 队列配置详情
                    $queue_info = Queue::where('id',$pro_info['queue'])->first();

                    // 系统自动发起兑换申请
                    $exchange = new ExChange;
                    $exchange->userid           = $pro_info['user_id'];                                 // 用户
                    $exchange->order_id         = $pro_info['order_id'];                                // 订单号
                    $exchange->shop_id          = $pro_info['delivery_point'];                          // 商户id
                    $exchange->total            = $pro_info['money'];                                   // 订单总额
                    $exchange->actual           = $pro_info['money'] * (1-$queue_info['poundage']/100); // 实际获得
                    $exchange->poundage         = $pro_info['money'] * $queue_info['poundage'] / 100;   // 利润 -- 金额
                    $exchange->percent          = $queue_info['poundage'].' %';                         // 利润 -- 百分比
                    $exchange->save();

                    // 剩余利润
                    $pro_money = $pro_money-$need;      
                }else{
                    // 本次获取的收益
                    $get_pro = $pro_money;

                    // 获益后继续排队中
                    $re_pay_pro = Lines::where('order_id',$pro_info['order_id'])
                                ->update([
                                    'proceeds'          => $pro_info['proceeds'] + $pro_money,
                                    'assist_proceeds'   => $pro_info['assist_proceeds']+$pro_money,
                                ]);

                    // 利润清零
                    $pro_money = 0;
                }

                // 收益日志
                $pro_log[] = [
                    'order_id'      => $pro_info['order_id'],
                    'queue'         => $pro_info['queue'],
                    'type'          => 2,                                   // 类型 2分润助推
                    'help_order'    => $order_sn,                           // 助推订单
                    'help_money'    => $get_pro,                            // 助推金额
                    'log'           => "获得助推收益".$get_pro." 积分",
                    'created_at'    => date("Y-m-d H:i:s"),
                    'updated_at'    => date("Y-m-d H:i:s")
                ];

            }while($pro_money>0);

            // 收益日志入库
            $res = LinesLog::insert($pro_log);

            // 提交事务
            DB::commit();

        } catch (\Exception $e) {

            // 回滚事务
            DB::rollback();

            // die($e);
        }
    }
}
